package com.meng.shiro;

import com.meng.pojo.TUser;
import com.meng.service.UserService;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class CustomRealm extends AuthorizingRealm{

	@Autowired
	private UserService userService;

	public String getName(){
		return this.getClass().getSimpleName();
	}

	/**
	 * 认证
	 * 表单认证过滤器认证时会调用自定义Realm的认证方法进行认证
	 * 前提：表单认证过滤器收集和组织用户名和密码信息封装为token对象传递给此方法
	 * token:封装了身份信息和凭证信息 2步骤：比对身份 信息；比对凭证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

	    //获取用户输入的用户名
	      String username = token.getPrincipal().toString();

          //根据用户名从数据库中查询密码信息和盐
          TUser tUser = userService.queryUsernamebyName(username);

          if (tUser!=null){
          	AuthenticationInfo info = new SimpleAuthenticationInfo(tUser,tUser.getPassword(), ByteSource.Util.bytes(tUser.getSalt()),getName());
          	return info;
		    }else {
          	return null;
		  }

	}

	/**
	 * 授权
	 * realm授权方法 从输入参数principalCollection得到身份信息 根据身份信息到数据库查找权限信息 将权限信息添加给授权信息对象
	 * 返回 授权信息对象(判断用户访问url是否在权限信息中没有体现)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		TUser username=(TUser) principalCollection.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		TUser user = userService.queryUsernamebyName(username.getUsername());
		if(user!=null){
			List<Integer> rolesid = userService.queryrolesid(user.getUserId());
			List<Integer> permissionsid = new ArrayList<Integer>();
			for(int i:rolesid){
				permissionsid.addAll(userService.querypermissoinsid(i));
			}
			for(int o:permissionsid){
				String code = userService.querypermission(o).getCode();
				
				System.out.println(code);
				info.addStringPermission(code);
			}
		}
		return info;
	}
}
